package com.mobile.socketserver;

import android.util.Log;

import com.mobile.socketclient.Message;

import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Map;

public class NotifyHandler extends Thread {

    private static final String TAG = "NotifyHandler";
    Socket socket;
    InputStream in = null;
    Map<Integer, Socket> sessionMap;

    public NotifyHandler(Socket socket, Map<Integer, Socket> sessionMap) {
        this.socket = socket;
        this.sessionMap = sessionMap;
    }

    public void run() {
        try {
            Log.e(TAG, "run: 线程while循环外部执行了" );
            in = socket.getInputStream();
            ObjectInputStream ois = new ObjectInputStream(in);
            // 实现一次连接多次通话
            while (true) {
                try {
                    Message msg = (Message) ois.readObject();
                    Log.e(TAG, "消息接受对象：客户端" + msg.getId() + "，消息内容：" + msg.getMsg());
                    Log.e(TAG, "socket.isConnected():"+socket.isConnected());
                    // 发送数据
                    try {
                        Socket targetSocket = sessionMap.get(1);
                        OutputStream out = targetSocket.getOutputStream();
                        ObjectOutputStream oos = new ObjectOutputStream(out);
                        oos.writeObject(msg);
                        Log.e(TAG, "服务端转发数据给客户端:" + msg.getMsg()+" yeah!server");
                    } catch (IOException e) {
                        Log.e(TAG, "服务端发现关闭流了1");
                        e.printStackTrace();
                    }
                    if (socket.isClosed()) {
                        Log.e(TAG, "服务端发现关闭流了2");
                        break;
                    }
                } catch (IOException e) {
                    Log.e(TAG, "服务端发现关闭流了3");
                    e.printStackTrace();
                    try {
                        socket.close();
                        break;
                    } catch (IOException e1) {
                        Log.e(TAG, "服务端发现关闭流了4");
                        e1.printStackTrace();
                    }
                } catch (ClassNotFoundException e) {
                    Log.e(TAG, "服务端发现关闭流了5");
                    e.printStackTrace();
                }
            }
        } catch (IOException e) {
            Log.e(TAG, "服务端发现关闭流了6");
            e.printStackTrace();
        }
    }
}
